package com.wayne.advice;

import com.wayne.exceptions.CheckException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.support.WebExchangeBindException;

/**
 * 异常处理切面
 */
@ControllerAdvice
public class CheckAdvice {
    @ExceptionHandler(WebExchangeBindException.class)
    public ResponseEntity handleBindException(WebExchangeBindException ex) {
        return new ResponseEntity<String>(toStr(ex), HttpStatus.BAD_REQUEST);
    }

    private String toStr(WebExchangeBindException ex) {
        return ex.getFieldErrors().stream()
                .map(e -> e.getField() + "：" + e.getDefaultMessage())
                .reduce("", (s1, s2) -> s1 + "\n" + s2);
    }

    @ExceptionHandler(CheckException.class)
    public ResponseEntity handleCheckException(CheckException ex) {
        return new ResponseEntity<String>(ex.getFeildName() + " 错误的值 :" + ex.getFeildValue(), HttpStatus.BAD_REQUEST);
    }
}
